package myUser;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oamMyvisit.Visitor;

/**
 * Servlet implementation class CheckExists
 */
@WebServlet("/CheckExists")
public class CheckExists extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CheckExists() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		request.setCharacterEncoding("UTF-8");
		String name=request.getParameter("username");
		int id=0;
		try {
			UserDao dao=new UserDao();
			id=dao.getIdbyName(name);
		} catch (NamingException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		response.setCharacterEncoding("UTF-8");
		PrintWriter out=response.getWriter();
		if(id==0) {
			out.println("该用户不存在！");
			return;
		}
		
		//判断数据库是否有当前用户
		ServletContext application = request.getServletContext();
		@SuppressWarnings("unchecked")
		HashMap<String,Visitor> map=(HashMap<String, Visitor>) application.getAttribute("ONLINE");
		Set<String> ids=map.keySet();
		Iterator<String> it=ids.iterator();
		String sid="";
		Visitor current=null;
		
		while(it.hasNext()) {
			sid=it.next();
			Visitor v=map.get(sid);
			if(v.getUserId()==id) {
				current=v;
				break;
			}
		}
			
		response.setCharacterEncoding("UTF-8");
		if(current!=null) {//已登录
			out.println("该用户已在["+current.getIp()+"]登录");
		}
	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
